<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\CommonController as Base;
use App\Http\Controllers\SmsController;
use App\Models\CollArea;
use App\Models\CollPosition;
use App\Models\CompanyUser;
use App\Models\DeviceInfo;
use App\Models\PersonalUser;
use App\Models\Product;
use App\Models\WebConfig;
use Illuminate\Http\Request;
use App\Http\Controllers\UploadController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CommonController extends Base
{

    protected static $baseImg = 'https://liande.oss-cn-beijing.aliyuncs.com';
    protected static $totalList = 10;

    public function allPositions()
    {
        $positions = CollPosition::getFirstPosition();
        if ($positions) {
            foreach ($positions as $v) {
                $v->child;
            }

            foreach ($positions as $v) {
                if ($v->child) {
                    foreach ($v->child as $val) {
                        $val->img1 = self::$baseImg . '/' . $val->img1;
                    }
                };
            }
        }
        return response()->json(['status' => 1, 'data' => ['positions' => $positions]]);
    }

    public function secondPosition($cid)
    {
        $positions = CollPosition::getSecondPosition($cid);
        $products = [];
        if ($positions) {
            foreach ($positions as $v) {
                $pinfos = Product::where('work_id', $v['id'])->where('status', 1)->get();
                if ($pinfos) {
                    foreach ($pinfos as $val) {
                        $val->cover_ico = self::$baseImg . '/' . $val->cover_ico;
                        array_push($products, $val);
                    }
                }
            }
        }
        return response()->json(['status' => 1, 'data' => ['positions' => $positions, 'products' => $products]]);
    }

    public function allSearch()
    {
        //地区
        $son = [
            0 => [
                'name' => '全国', 'value' => 0
            ]
        ];
        $firstAreas = CollArea::where('grade', 1)->select('cid', 'name')->orderBy('id', 'asc')->get();
        foreach ($firstAreas as $v1) {
            $sons = CollArea::where('grade', 2)->where('pid', $v1['cid'])->select('cid', 'name')->orderBy('id', 'asc')->get();
            if (count($sons) > 0) {
                $sonsArr = [];
                foreach ($sons as $v2) {
                    $sonss = CollArea::where('grade', 3)->where('pid', $v2['cid'])->select('cid', 'name')->orderBy('id', 'asc')->get();

                    if (count($sonss) > 0) {
                        $sonssArr = [];
                        foreach ($sonss as $v3) {
                            $sonssArr[] = [
                                'name' => $v3->name,
                                'value' => $v3->cid
                            ];
                        }
                        $sonsArr[] = [
                            'name' => $v2->name,
                            'value' => $v2->cid,
                            'submenu' => $sonssArr
                        ];
                    } else {
                        $sonsArr[] = [
                            'name' => $v2->name,
                            'value' => $v2->cid
                        ];
                    }
                }
                $son[] = [
                    'name' => $v1->name,
                    'value' => $v1->cid,
                    'submenu' => $sonsArr
                ];
            } else {
                $son[] = [
                    'name' => $v1->name,
                    'value' => $v1->cid
                ];
            }
        }

        //工种
        $position = [
            0 => [
                'name' => '不限', 'value' => 0
            ]
        ];
        $firstPositions = CollPosition::where('grade', 1)->select('cid', 'name')->orderBy('id', 'asc')->get();
        foreach ($firstPositions as $v11) {
            $sons1 = CollPosition::where('grade', 2)->where('pid', $v11['cid'])->select('cid', 'name')->orderBy('id', 'asc')->get();
            if (count($sons1) > 0) {
                $sons1Arr = [];
                foreach ($sons1 as $v22) {
                    $sons1Arr[] = [
                        'name' => $v22->name,
                        'value' => $v22->cid
                    ];
                }
                $position[] = [
                    'name' => $v11->name,
                    'value' => $v11->cid,
                    'submenu' => $sons1Arr
                ];
            } else {
                $position[] = [
                    'name' => $v11->name,
                    'value' => $v11->cid
                ];
            }
        }

        //薪资
        $salarys = WebConfig::getConfig('salary');
        $salarysArr = [];
        if ($salarys) {
            $salarys1 = explode(',', $salarys);
            foreach ($salarys1 as $v111) {
                $arr = explode(':', $v111);
                $salarysArr[] = [
                    "name" => $arr[1] . "元",
                    "value" => $arr[0]
                ];
            }
        }

        $area = [
            [
                "name" => '地区',
                "type" => 'hierarchy-column',
                'submenu' => $son
            ],
            [
                "name" => '工种',
                "type" => 'hierarchy-column',
                'submenu' => $position
            ],
            [
                "name" => '薪资',
                "type" => 'radio',
                'submenu' => [
                    [
                        "name" => "薪资(单选)",
                        "submenu" => $salarysArr
                    ]
                ],
            ]

        ];

        return response()->json(['status' => 1, 'data' => $area]);
    }

    public function allSearch1()
    {
        //地区
        $son = [
            0 => [
                'name' => '全国', 'value' => 0
            ]
        ];
        $firstAreas = CollArea::where('grade', 1)->select('cid', 'name')->orderBy('id', 'asc')->get();
        foreach ($firstAreas as $v1) {
            $sons = CollArea::where('grade', 2)->where('pid', $v1['cid'])->select('cid', 'name')->orderBy('id', 'asc')->get();
            if (count($sons) > 0) {
                $sonsArr = [];
                foreach ($sons as $v2) {
                    $sonss = CollArea::where('grade', 3)->where('pid', $v2['cid'])->select('cid', 'name')->orderBy('id', 'asc')->get();

                    if (count($sonss) > 0) {
                        $sonssArr = [];
                        foreach ($sonss as $v3) {
                            $sonssArr[] = [
                                'name' => $v3->name,
                                'value' => $v3->cid
                            ];
                        }
                        $sonsArr[] = [
                            'name' => $v2->name,
                            'value' => $v2->cid,
                            'submenu' => $sonssArr
                        ];
                    } else {
                        $sonsArr[] = [
                            'name' => $v2->name,
                            'value' => $v2->cid
                        ];
                    }
                }
                $son[] = [
                    'name' => $v1->name,
                    'value' => $v1->cid,
                    'submenu' => $sonsArr
                ];
            } else {
                $son[] = [
                    'name' => $v1->name,
                    'value' => $v1->cid
                ];
            }
        }

        //薪资
        $salarys = WebConfig::getConfig('salary');
        $salarysArr = [];
        if ($salarys) {
            $salarys1 = explode(',', $salarys);
            foreach ($salarys1 as $v111) {
                $arr = explode(':', $v111);
                $salarysArr[] = [
                    "name" => $arr[1] . "元",
                    "value" => $arr[0]
                ];
            }
        }

        $area = [
            [
                "name" => '地区',
                "type" => 'hierarchy-column',
                'submenu' => $son
            ],
            [
                "name" => '薪资',
                "type" => 'radio',
                'submenu' => [
                    [
                        "name" => "薪资(单选)",
                        "submenu" => $salarysArr
                    ]
                ]
            ]
        ];

        return response()->json(['status' => 1, 'data' => $area]);
    }

    public function allSearchc()
    {
        //地区
        $son = [
            0 => [
                'name' => '全国', 'value' => 0
            ]
        ];
        $firstAreas = CollArea::where('grade', 1)->select('cid', 'name')->orderBy('id', 'asc')->get();
        foreach ($firstAreas as $v1) {
            $sons = CollArea::where('grade', 2)->where('pid', $v1['cid'])->select('cid', 'name')->orderBy('id', 'asc')->get();
            if (count($sons) > 0) {
                $sonsArr = [];
                foreach ($sons as $v2) {
                    $sonss = CollArea::where('grade', 3)->where('pid', $v2['cid'])->select('cid', 'name')->orderBy('id', 'asc')->get();

                    if (count($sonss) > 0) {
                        $sonssArr = [];
                        foreach ($sonss as $v3) {
                            $sonssArr[] = [
                                'name' => $v3->name,
                                'value' => $v3->cid
                            ];
                        }
                        $sonsArr[] = [
                            'name' => $v2->name,
                            'value' => $v2->cid,
                            'submenu' => $sonssArr
                        ];
                    } else {
                        $sonsArr[] = [
                            'name' => $v2->name,
                            'value' => $v2->cid
                        ];
                    }
                }
                $son[] = [
                    'name' => $v1->name,
                    'value' => $v1->cid,
                    'submenu' => $sonsArr
                ];
            } else {
                $son[] = [
                    'name' => $v1->name,
                    'value' => $v1->cid
                ];
            }
        }

        //工种
        $position = [
            0 => [
                'name' => '不限', 'value' => 0
            ]
        ];
        $firstPositions = CollPosition::where('grade', 1)->select('cid', 'name')->orderBy('id', 'asc')->get();
        foreach ($firstPositions as $v11) {
            $sons1 = CollPosition::where('grade', 2)->where('pid', $v11['cid'])->select('cid', 'name')->orderBy('id', 'asc')->get();
            if (count($sons1) > 0) {
                $sons1Arr = [];
                foreach ($sons1 as $v22) {
                    $sons1Arr[] = [
                        'name' => $v22->name,
                        'value' => $v22->cid
                    ];
                }
                $position[] = [
                    'name' => $v11->name,
                    'value' => $v11->cid,
                    'submenu' => $sons1Arr
                ];
            } else {
                $position[] = [
                    'name' => $v11->name,
                    'value' => $v11->cid
                ];
            }
        }

        //经验
        $workYears = WebConfig::getConfig('work_year');
        $workYearsArr = [];
        if ($workYears) {
            $workYears1 = explode(',', $workYears);
            foreach ($workYears1 as $v111) {
                $arr = explode(':', $v111);
                $workYearsArr[] = [
                    "name" => $arr[1] . "年",
                    "value" => $arr[0]
                ];
            }
        }
        $area = [
            [
                "name" => '地区',
                "type" => 'hierarchy-column',
                'submenu' => $son
            ],
            [
                "name" => '工种',
                "type" => 'hierarchy-column',
                'submenu' => $position
            ],
            [
                "name" => '经验',
                "type" => 'radio',
                'submenu' => [
                    [
                        "name" => "工作经验(单选)",
                        "submenu" => $workYearsArr
                    ]
                ],
            ],
            [
                "name" => '性别',
                "type" => 'radio',
                'submenu' => [
                    [
                        "name" => "性别(单选)",
                        "submenu" => [
                            [
                                'name' => '不限',
                                'value' => 0
                            ],
                            [
                                "name" => "男",
                                "value" => "1"
                            ],
                            [
                                "name" => "女",
                                "value" => "2"
                            ]
                        ]
                    ]
                ],
            ],
        ];

        return response()->json(['status' => 1, 'data' => $area]);
    }

    /**
     * 上传图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadImg(Request $request)
    {
        $fileInfo = $_FILES['file'];
        if (!$fileInfo) {
            return response()->json(['status' => 0, 'msg' => '上传失败']);
        }

        if (!in_array($fileInfo['type'], ["image/png", "image/jpg", "image/jpeg", "image/gif", "video/avi", "video/mp4", "video/rm", "video/rmvb", "video/quicktime"])) {
            return response()->json(['status' => 0, 'msg' => '文件类型错误！']);
        }

//        Log::debug($fileInfo);
        $size = ceil($fileInfo['size'] / (1024 * 1024));
        if ($size > 20) {
            return response()->json(['status' => 0, 'msg' => '资源大于20M！']);
        }

        $remoteDir = config("filesystems.disks.oss.ad_upload_dir");
        $upload = new UploadController();
        $res = $upload->doUpload($request->file, $remoteDir);

        if ($res['status'] == 0) {
            return response()->json(['status' => 0, 'msg' => '上传失败']);
        }

        return response()->json(['status' => 1, 'msg' => '上传成功', 'data' => $res['fileUrl']]);
    }

    /**
     * 绑定微信
     */
    public function bindWx(Request $request)
    {
        $openId = $request->openId;
        $type = $request->type;
        $openIdField = 'openid' . $type;

        $wxInfo = DB::table('weixin_info')->where($openIdField, $openId)->first();
        if ($wxInfo) {
            $id = $wxInfo->id;
        } else {
            $nickName = $request->nickName;
            $headimg = $request->avatarUrl;
            $unionId = $request->unionId;
            $data = [
                'nickname' => $nickName,
                'headimg' => $headimg,
                $openIdField => $openId
            ];

            if ($unionId) {
                $data['unionid'] = $unionId;
            }

            $id = DB::table('weixin_info')->insertGetId($data);
        }

        $uid = $request->uid;
        $cate = $request->cate;
        switch ($cate) {
            case 1:
                $res = PersonalUser::where('uid', $uid)->update(['wechatid' => $id]);
                break;
            case 2:
                $res = CompanyUser::where('uid', $uid)->update(['wechatid' => $id]);
                break;
        }

        if ($res) {
            return response()->json(['status' => 1, 'msg' => '绑定成功', 'data' => $id]);
        } else {
            return response()->json(['status' => 0, 'msg' => '绑定失败']);
        }
    }

    /**
     * 计算两点之间的距离
     * @param $lat1
     * @param $lng1
     * @param $lat2
     * @param $lng2
     * @return int
     */
    function getDistance($lat1, $lng1, $lat2, $lng2, $radius = 6378.137)
    {
        $rad = floatval(M_PI / 180.0);

        $lat1 = floatval($lat1) * $rad;
        $lon1 = floatval($lng1) * $rad;
        $lat2 = floatval($lat2) * $rad;
        $lon2 = floatval($lng2) * $rad;

        $theta = $lon2 - $lon1;

        $dist = acos(sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($theta));

        if ($dist < 0) {
            $dist += M_PI;
        }
        return $dist = $dist * $radius;

    }

    /**
     * @author gayayang
     * @date 2012-8-21
     * @todo 将对象转换成数组
     * @param unknown_type $obj
     * @return unknown
     */
    function object_to_array($object)
    {
        if (is_object($object)) {
            foreach ($object as $key => $value) {
                $value = is_object($value) ? get_object_vars($value) : $value;
                $array[$key] = $value;
            }
        } else {
            $array = $object;
        }
        return $array;
    }

    /**
     * 验证短信验证码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkCode(Request $request)
    {
        $mobile = trim($request->mobile);
        $code = trim($request->code);
        if (!$mobile || !$code) {
            return response()->json(['status' => 0, 'msg' => '手机号码或者短信验证码缺失！']);
        }

        if (strlen($mobile) != 11) {
            return response()->json(['status' => 0, 'msg' => '手机号码必须是11位数！']);
        }
        preg_match("/1[3-9]{1}\d{9}/", $mobile, $result);
        if (!$result) {
            return response()->json(['status' => 0, 'msg' => '手机号码格式错误！']);
        }

        $sms = new SmsController();
        $res = $sms->checkCode($mobile, $code);
        if ($res['status'] == 0) {
            return response()->json(['status' => 0, 'msg' => $res['msg']]);
        }

        return response()->json(['status' => 1, 'msg' => '短信验证成功']);
    }

    /**
     * 添加设备
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addDevice(Request $request)
    {
        $clientId = $request->client_id;
        $cate = $request->cate;
        $uid = $request->uid;
        $dInfo = DeviceInfo::where('device_id', $clientId)->first();
        if (!$dInfo) {
            $data = [
                'cate' => $cate,
                'uid' => $uid,
                'device_id' => $clientId,
            ];
            DeviceInfo::create($data);
            return response()->json(['status' => 1, 'msg' => '该设备注册成功']);
        }
        if ($dInfo->cate != $cate || $dInfo->uid != $uid) {
            $data = [
                'cate' => $cate,
                'uid' => $uid
            ];
            DeviceInfo::where('id', $dInfo->id)->update($data);
            return response()->json(['status' => 1, 'msg' => '该设备更新成功']);
        }

        return response()->json(['status' => 1, 'msg' => '该设备已完整注册']);
    }
}
